package edu.nyu.hps.assignment9;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.List;
import java.util.ArrayList;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int port = 22422, attributes = 0;
		boolean connected = false;
		String response = null;
		Socket client;

		// Socket handles
		InputStreamReader isr;
		BufferedReader in = null;
		PrintWriter out = null;

		// File handles
		BufferedReader fin = null; // new BufferedReader(new
		// FileReader(args[0]));
		if (args.length > 1) {
			port = Integer.parseInt(args[0]);
		}
		// Initialization
		try {
			client = new Socket("128.122.80.195", port);
			isr = new InputStreamReader(client.getInputStream());
			in = new BufferedReader(isr);
			out = new PrintWriter(client.getOutputStream(), true);

			while (!connected) {
				response = null;
				out.println("JOIN:Rohan");

				// Waiting for the ACK or NACK responses from the server
				while ((response = in.readLine()) == null) {
				}

				if (response.charAt(0) == 'A') {
					System.out.println("" + response);
					attributes = Integer.parseInt(response.split(":")[1]);
					System.out.println("Attributes[ "
							+ attributes + " ]");
					connected = true;
				}
			}

			Dating game = new Dating(attributes);

			while ((response = in.readLine()) == null) {
			}

			while (response.charAt(0) == 'C') {
				Candidate c = new Candidate(attributes);
				String[] tmpArr = response.split(":");
				List<Double> tmpArrList = new ArrayList<Double>();
				for (int i = 0; i < attributes; i++) {
					tmpArrList.add(Double.parseDouble(tmpArr[i + 2]));
				}
				c.attributes = tmpArrList.toArray(new Double[attributes]);
				c.setScore(Double.parseDouble(tmpArr[tmpArr.length - 1]));
				game.candidates.add(c);

				response = null;
				if (game.candidates.size() == 20) {
					break;
				}
				// Waiting for next candidate
				while ((response = in.readLine()) == null) {
				}
			}

			while (true) {
				Candidate c = game.getNewCandidates();
				out.print("DATE");
//				System.out.print("DATE");
				for(int i=0;i<attributes;i++){
					out.print(":");
					System.out.print(":");
					out.print(c.attributes[i]);
					System.out.print(c.attributes[i]);
				}
				out.println();
				System.out.println();
				
				while ((response = in.readLine()) == null) {
				}
				if(response.split(":")[0].equalsIgnoreCase("STATUS")){
					break;
				}
				System.out.println("Server: " + response);
				c.setScore(Double.parseDouble(response.split(":")[2]));
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}